/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * StatisticsDialog.java
 *
 * Created on Jul 11, 2010, 3:04:43 PM
 */

package org.foment.gem.statistic;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PrinterException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.foment.joliage3.sql.Database;

/**
 *
 * @author Dusan
 */
public class StatisticsDialog extends javax.swing.JFrame {

    // sve moguce kolone koje eventualno prikazujemo. Ovaj niz se koristi i u TableModel klasi
    // vazan je redosled!!! Nikako ne menjati!
    public static final String [] columns = {"#","Ime", "Prezime", "JMBG", "LBO", "Datum rodjenja", "Pozicija", "Predmet",
    "Radni staz", "Naučna oblast", "Angažovanost", "Od"};
    public static final String [] columnsEng = {"#","EmployeeFirstName", "EmployeeSurname", "EmployeeJMBG", "EmployeeLBO",
    "EmployeeDateOfBirth", "JobTypeTitle", "CourseTitle", "EmployeeTotalWorkTime", "ScienceDomainTitle", "EmployeeJobDetailsPartimeJobPercent", "EmployeeJobTypeStartDate"};
    private JPopupMenu _menu = new JPopupMenu();
    private TableModel _model;
    private JMenuBar _menuBar = new JMenuBar();
    private enum TYPE_OF_SELECTION {GENDER, POSITIONS, PARTIME};
    
    /** Creates new form StatisticsDialog */
    public StatisticsDialog()
    {
        // vazan je redosled poziva funkcija. Prvo moramo da ucitamo sve zaposlene!
        // nakon toga, postavljamo Menu objekat koji dodaje sve sto je selektoano u HashSet-ove
        // selectedGender i selectedPositions.
        //();
        Employee.loadEmployees();
        setMenu();
        initComponents();
        setComponents();
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    private void setComponents()
    {
        _model = new TableModel();
        // Rucno dodajemo kolonu za redni broj.
        _model.addColumn("#");

        for (String s : columns)
        {
            final JCheckBoxMenuItem jc = new JCheckBoxMenuItem(s);
            jc.setSelected(true);
            
            jc.setName(s);
            jc.addItemListener(new ItemListener() {

                public void itemStateChanged(ItemEvent e)
                {
                    if (jc.isSelected() == false)
                        _model.removeColumn(jc.getName());
                    else
                        _model.addColumn(jc.getName());
                    _model.refresh();
                }
            });
            _menu.add(jc);
        }
        
        table.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e) {
                _menu.show(table, e.getX(), e.getY());
            }
        });
        
        table.setModel(_model);
    }

    private void setMenu()
    {
        JMenu first = new JMenu("Program");
        JMenuItem mnuItemPrint = new JMenuItem("Štampa");
        mnuItemPrint.addActionListener( new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                print();
            }
        });
        JMenuItem mnuItemExit = new JMenuItem("Izlaz");
        mnuItemExit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                exit();
            }
        });
        first.add(mnuItemPrint);
        first.add(mnuItemExit);
        _menuBar.add(first);

        // dodajemo za podmenije za pol
        JMenu view = new JMenu("Prikaži");

        JMenu mnuItemGender = new JMenu("Pol");
        male.setSelected(true);
        female.setSelected(true); // inicijalno su selektovani i muskarci i zene.
        male.setName("m"); female.setName("f"); // postavljamo imena kontrolama
        // ona korespondiraju vrednosti atributa iz baze
        selectedGender.add("m"); selectedGender.add("f");
        male.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                handleMenuEvent(male.isSelected(), TYPE_OF_SELECTION.GENDER, male.getName());
            }
        });
        female.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                handleMenuEvent(female.isSelected(), TYPE_OF_SELECTION.GENDER, female.getName());
            }
        });
        mnuItemGender.add(male);
        mnuItemGender.add(female);
        view.add(mnuItemGender);
        view.addSeparator();

        // dodajemo podmeni za zaposleni sa punim/nepunim radnim vremenom
        JMenu mnuItemPartTime = new JMenu("Radno vreme");
        fullTime.setSelected(true);
        partime.setSelected(true);
        fullTime.setName("0"); partime.setName("1");
        selectedPartime.add("0"); selectedPartime.add("1");
        partime.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                handleMenuEvent(partime.isSelected(), TYPE_OF_SELECTION.PARTIME, partime.getName());
            }
        });
        fullTime.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e){
                handleMenuEvent(fullTime.isSelected(), TYPE_OF_SELECTION.PARTIME, fullTime.getName());
            }
        });
        mnuItemPartTime.add(fullTime);
        mnuItemPartTime.add(partime);
        view.add(mnuItemPartTime);
        view.addSeparator();
        
        //
        // dodajemo podmenije za pozicije.
        try
        {
            String query = "SELECT * FROM Job";
            Connection conn = Database.getConnection();
            ResultSet rs = conn.createStatement().executeQuery(query);
            while(rs.next())
            {
                int jobId = rs.getInt("JobID");
                String jobTitle = rs.getString("JobTitle");
                JMenu jmenu = new JMenu(jobTitle); // staviti za setName!!
                String query1 = "SELECT * FROM JobType WHERE JobId = '" + jobId + "' ;";
                Connection conn1 = Database.getConnection();
                ResultSet rs1 = conn1.createStatement().executeQuery(query1);
                while(rs1.next())
                {
                    String title = rs1.getString("JobTypeTitle");
                    final JCheckBoxMenuItem jcbm = new JCheckBoxMenuItem(title);
                    jcbm.setName(title);
                    //selectedPositions.add(title); // Inicijalno su sve pozicije selektovane
                    jcbm.setSelected(false);
                    jcbm.addActionListener(new ActionListener() {

                        public void actionPerformed(ActionEvent e)
                        {
                            handleMenuEvent(jcbm.isSelected(), TYPE_OF_SELECTION.POSITIONS, jcbm.getName());
                        }
                    });
                    jmenu.add(jcbm);
                }
                view.add(jmenu);
                rs1.close();
                conn1.close();
            }
            rs.close();
            conn.close();
        }
        catch(SQLException e) {e.printStackTrace();}
        
        _menuBar.add(view);
        this.setJMenuBar(_menuBar);
    }

    private void handleMenuEvent(boolean selected, TYPE_OF_SELECTION type, String value)
    {
        if (selected)
        {
            if (type == TYPE_OF_SELECTION.GENDER)
                selectedGender.add(value);
            else if( type == TYPE_OF_SELECTION.POSITIONS )
                selectedPositions.add(value);
            else
                selectedPartime.add(value);
        }
        else
        {
            if (type == TYPE_OF_SELECTION.GENDER)
                selectedGender.remove(value);
            else if( type == TYPE_OF_SELECTION.POSITIONS )
                selectedPositions.remove(value);
            else
                selectedPartime.remove(value);
        }
        _model.refresh();
    }
    
    private void print()
    {
         try {
            // pozovi stampanje
            MessageFormat header = new MessageFormat("Statistika zaposlenih");
            MessageFormat footer = new MessageFormat("Strana {0}");

            // first we add empty row in the table, followed by row which contains
            // total rows count information

            int rowCount    = table.getRowCount();

            //DefaultTableModel mod = (DefaultTableModel) table.getModel();
            //mod.insertRow(rowCount, new Object[]{""});
            //mod.insertRow(rowCount+1, new Object[]{"Ukupno: " + rowCount});

            // setting other params...
            PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
            attributeSet.add(MediaSizeName.ISO_A4);
            attributeSet.add(OrientationRequested.LANDSCAPE);
            

            //java.awt.Font font = table.getFont();
            table.setFont( new java.awt.Font( table.getFont().getName(), java.awt.Font.PLAIN, 14 ) );
            //System.out.println( font.getSize() );
            boolean result = table.print(JTable.PrintMode.FIT_WIDTH,
                      header,
                      footer,
                      true,
                      attributeSet,
                      true,
                      null);

            if (result) {
                System.out.println("Printing success!");
            } else {
                System.out.println("Printing failed!");
            }

        } catch (PrinterException ex) {
            Logger.getLogger(StatisticsDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void showDialog()
    {
         Employee.loadEmployees();
        _model.refresh();
        this.setVisible(true);
    }
    private void exit()
    {
        this.dispose();
    }
    /*
    private void loadEmployees()
    {
        Employee.reset();
        
        String query = "SELECT * FROM Employee ORDER BY EmployeeSurname";
        try
        {
            ResultSet rs = Database.getConnection().createStatement().executeQuery(query);
            //System.out.println("=============================================");
            while(rs.next())
            {
                Employee e = new Employee(rs.getInt("EmployeeID"));
                e.setValues(rs);
                //System.out.println("Retrieved: " + rs.getString("EmployeeSurname") );
            }
            rs.close();
        }
        catch(SQLException e) {e.printStackTrace();}
    }
     * */
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(table);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 777, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
    

    private JCheckBoxMenuItem male = new JCheckBoxMenuItem("Muški");
    private JCheckBoxMenuItem female = new JCheckBoxMenuItem("Ženski");

    private JCheckBoxMenuItem fullTime = new JCheckBoxMenuItem("Puno radno vreme");
    private JCheckBoxMenuItem partime = new JCheckBoxMenuItem("Nepuno radno vreme");
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables

    public static Set<String> selectedPositions = new HashSet<String>(); // pozicije koje su izabrane
    public static Set<String> selectedGender = new HashSet<String>(2); // za izabrani pol
    public static Set<String> selectedPartime = new HashSet<String>(2);
}
